package com.warehouse.dao.impl;

import com.warehouse.dao.AdminDao;
import com.warehouse.dao.common.HibernateUtil;
import com.warehouse.entity.Admin;
import org.hibernate.Query;

import java.util.List;

public class AdminDaoImpl implements AdminDao {
    @Override
    public int add(Admin admin) {
        try {
            HibernateUtil.currentSession().save(admin);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int update(Admin admin) {
        try {
            HibernateUtil.currentSession().update(admin);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int delete(int id) {
        try {
            //先获取id
            Admin admin = (Admin) HibernateUtil.currentSession().get(Admin.class, id);
            HibernateUtil.currentSession().delete(admin);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    //分页查询
    @Override
    public List<Admin> allPage(int startPage, int pageSize) {
        Query query = HibernateUtil.currentSession().createQuery("from Admin");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    //查询总条数
    @Override
    public int count() {
        return HibernateUtil.currentSession().createQuery("from Admin").list().size();
    }

    //根据id查询全部信息
    @Override
    public Admin byId(int id) {
        Admin admin = (Admin) HibernateUtil.currentSession().get(Admin.class, id);
        return admin;
    }

    //登录方法
    @Override
    public Admin Login(String phone, String password) {
        Query query = HibernateUtil.currentSession().createQuery("from Admin a where a.phone=? and a.password=?");
        query.setString(0, phone);
        query.setString(1, password);
        //  返回唯一因为管理员的账户不能重复 返回uniqueResult
        return (Admin) query.uniqueResult();
    }

    //分页模糊查询
    @Override
    public List<Admin> byAdminNum(int startPage, int pageSize, String name) {
        Query query = HibernateUtil.currentSession().createQuery("from Admin a where a.name like '%" + name + "%'");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    //分页模糊查询出来的条数
    @Override
    public int countByAdminNum(String name) {
        return HibernateUtil.currentSession().createQuery("from Admin a where a.name like '%" + name + "%'").list().size();

    }
}
